

(async () => {
    const html = `
        <style>
        #ScriptRoot {
            position: fixed;
            right: 50px;
            bottom: 50px;
        }

        #ScriptRoot .context {
            width: 500px;
            position: absolute;
            left: -100%;
            top: -100%;
        }

        .dialog {
            background: #fff;
            padding: 15px;
            position: fixed;
            z-index: 10000;
            left: 50%;
            top: 50%;
            transform: translateX(-50%) translateY(-50%);
            box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.3);
            border-radius: 15px;
            overflow-y: auto;
            max-height: 500px;
        }

        .dialogBtn {
            text-align: center;
            padding-top: 15px;
        }

        .dialogBtn button {
            cursor: pointer;
            padding-left: 15px;
            padding-right: 15px;
            height: 30px;
            background: #3f74e3;
            color: #fff;
            font-size: 14px;
            text-shadow: 1px -1px 0 rgba(0, 0, 0, 0.5);
            border: none;
            border-radius: 5px;
        }

        .dialogBtn button:hover {
            background: #1846a8;
        }

        .dialogContent {
            min-width: 500px;
            min-height: 80px;
            font-size: 16px;
            line-height: 1.5;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #ScriptContent {
            display: flex;
            gap: 2;
        }
    </style>
    <div id="ScriptRoot">
        <div>
            <textarea style="width:500px;height:400px" id="ScriptAnalysis"></textarea>
            <button id="ScriptStart">开始</button>
        </div>
    </div>
    `
    const container = document.createElement("div");
    container.innerHTML = html;
    document.body.appendChild(container)
    const startBtn = document.getElementById("ScriptStart")
    const ScriptAnalysis = document.getElementById("ScriptAnalysis");
    const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    let menu;
    do {
        try {
            const menuList = Array.from(document.getElementsByClassName("submenu-wrapper")[0].children);
            menu = menuList.reduce((acc, item) => {
                acc[item.getElementsByTagName("span")[1].innerText] = item;
                return acc
            }, {});
        } catch (e) { }
        await sleep(500);
    } while (!menu);
    let status = false;
    let time;
    const getIframeDocument = () => {
        const iframe = document.getElementsByTagName("iframe")[0];
        const iframeDocument = iframe.contentWindow.document
        return iframeDocument
    }
    const getQueryButton = async () => {
        const iframeDocument = getIframeDocument();
        let button;
        do {
            try {
                button = iframeDocument.getElementsByClassName("el-button query-btn el-button--primary")[0]
            } catch (e) { }
            await sleep(500);
        } while (!button)
        return button
    }
    const query = async () => {
        const btn = await getQueryButton();
        btn.click();
        await sleep(1000)
        const iframeDocument = getIframeDocument();
        const task = iframeDocument.getElementsByClassName("task")[0];
        let text = "";
        do {
            try {
                await sleep(100)
                const num = task.getElementsByClassName("num")[0];
                text = num.innerText;
            } catch (e) { }
        } while (text.includes("加载中") || !text);
        return text.split("").reduce((count, word) => {
            const n = parseInt(word);
            if (!word || isNaN(n)) return count;
            return count * 10 + n;
        }, 0);
    }
    const getQueryItems = async () => {
        let header
        do {
            const iframeDocument = getIframeDocument()
            header = iframeDocument.getElementsByClassName("header")[0];
            await sleep(1000);
        } while (!header);
        return Array.from(header.getElementsByClassName("query-item"));
    }
    const getDomItems = async (dom) => {
        const iframeDocument = getIframeDocument()
        dom.getElementsByTagName("input")[0].click();
        await sleep(500)
        const item = Array.from(iframeDocument.getElementsByClassName("el-select-dropdown el-popper")).find(e => {
            return e.style.display !== "none";
        });
        await sleep(500)
        dom.getElementsByTagName("input")[0].click();
        return Array.from(item.getElementsByTagName("li"))
    }
    const workflow = [{
        name: "文本审核",
        children: [{
            name: "人工审核（初审）",
            children: [
                "union_report_combinationdesc_c",
                "union_report_combinationname_c",
                "union_report_farmdesc_c",
                "union_report_farmmessage_c",
                "union_report_groupcontent_c",
                "union_report_groupcontent_e",
                "union_report_groupname_c",
                "union_report_groupname_e",
                "union_report_homedesc_c",
                "union_report_homemessage_c",
                "union_report_homewelcome_c",
                "union_report_mapdesc_c",
                "union_report_mapname_c",
                "union_report_name_c",
                "union_report_roomname_c",
                "union_report_sign_c",
                "union_report_talk_c",
                "yuanmeng_diy_text",
                "union_report_homename_c"
            ]
        }, {
            name: "人工审核（二审）",
            children: [
                "union_report_combinationdesc_c",
                "union_report_combinationname_c",
                "union_report_farmdesc_c",
                "union_report_farmmessage_c",
                "union_report_groupcontent_c",
                "union_report_groupcontent_e",
                "union_report_groupname_c",
                "union_report_groupname_e",
                "union_report_homedesc_c",
                "union_report_mapdesc_c",
                "union_report_mapname_c",
                "union_report_name_c",
                "union_report_roomname_c",
                "union_report_sign_c",
                "union_report_talk_c",
                "union_report_homename_c"

            ]
        }]
    }, {
        name: "图片审核",
        children: [{
            name: "人工审核（初审）",
            children: [
                "举报",
                "封面"
            ]
        }, {
            name: "人工审核（二审）",
            children: [{
                name: "举报",
                children: [
                    "129组合",
                    "130家园",
                    "多人测试举报",
                    "家园封面"

                ]
            }, {
                name: "封面",
                children: [
                    "141组合封面",
                    "178家园派对封面",
                    "179家园封面"
                ]
            }]
        }]
    }, {
        name: "富文本审核",
        children: [{
            name: "富文本审核（初审）",
            children: [
                "defaultchannel",
                "上架",
                "剧情图片",
                "本地图片",
                "高热"
            ]
        }, {
            name: "富文本审核（二审）",
            children: [{
                name: "上架",
                children: [
                    "129组合",
                    "130家园"
                ]
            },
                "剧情图片",
                "本地图片"
            ]
        }]
    }];
    const dataToObj = (tree) => {
        const obj = {};
        for (const item of tree) {
            if (typeof item === "string") {
                obj[item] = 0;
            } else {
                obj[item.name] = dataToObj(item.children);
            }
        }
        return obj;
    }
    const renderText = dataToObj(workflow);
    console.log(renderText)
    const render = () => {
        let str = "";
        const objSum = (obj) => {
            let total = 0;
            for (const key in obj) {
                if (typeof obj[key] === "number") total += obj[key];
                else total += objSum(obj[key]);
            }
            return total;
        }
        const objAdd = (objA, objB) => {
            const obj = {};
            for (const key in objA) {
                obj[key] = objA[key];
            }
            for (const key in objB) {
                if (!obj[key]) obj[key] = 0;
                obj[key] += objB[key]
            }
            const arr = Object.keys(obj);
            return arr.map((name) => ({ name, count: obj[name] }));
        }
        const result = [{
            name: "富文本上架",
            count: renderText["富文本审核"]["富文本审核（初审）"]["上架"] + objSum(renderText["富文本审核"]["富文本审核（二审）"]["上架"])
        }, {
            name: "图片举报",
            count: objSum(renderText["图片审核"]["人工审核（二审）"]["举报"]) + renderText["图片审核"]["人工审核（初审）"]["举报"]
        }, {
            name: "图片封面",
            count: objSum(renderText["图片审核"]["人工审核（二审）"]["封面"]) + renderText["图片审核"]["人工审核（初审）"]["封面"]
        }, {
            name: "富文本高热",
            count: objSum(renderText["富文本审核"]["富文本审核（初审）"]["高热"])
        }, {
            name: "一审",
            children: objAdd(renderText["文本审核"]["人工审核（初审）"], {})
        }, {
            name: "二审",
            children: objAdd(renderText["文本审核"]["人工审核（二审）"])
        }];
        const strLen = (s) => {
            return (s + new Array(5).fill(" ").join("")).slice(0, 5)
        }
        const getStr = (obj) => {
            if (!obj) return;
            for (const key in obj) {
                if (typeof obj[key] === "number") {
                    str += `${strLen(obj[key])}    ${key}\n`;
                } else {
                    str += key + "\n";
                    getStr(obj[key])
                }
            }
        }
        getStr(renderText)
        ScriptAnalysis.value = str;
    }
    const setThreeDay = async () => {
        const iframeDocument = getIframeDocument();
        const label = Array.from((iframeDocument.getElementsByClassName("el-radio-button"))).find(e => e.innerText === "近3天")
        if (!label) return;
        label.getElementsByTagName("input")[0].click()
    }
    const queryAndRender = async (arr, key) => {

        const num = await query();
        let obj = renderText;
        for (const key of arr) {
            obj = obj[key];
        }
        obj[key] = num;
        console.log(arr, key, num);
        render();
        await sleep(500)
    }

    let currentKey;
    let currentTypeMenu = {};
    const setCurrentTypeMenu = async (key) => {
        menu[key].click()
        await sleep(1000);
        const [typeItem, valueItem] = await getQueryItems();
        const types = await getDomItems(typeItem);
        currentTypeMenu = {};
        for (const type of types) {
            type.click();
            const name = type.innerText;
            const menu = await getDomItems(valueItem);
            currentTypeMenu[name] = {
                dom: type,
                menu
            }
        }
    }
    let currentTypeMenuCopy = {};
    const setCurrentCopyMenu = async () => {
        const [typeItem, valueItem, lineItem] = await getQueryItems();
        const types = await getDomItems(lineItem);
        for (const type of types) {
            currentTypeMenuCopy[type.innerText] = type
        }
    }
    function* factor() {
        for (const menu of workflow) {
            const key = menu.name;
            if (currentKey !== key) {
                currentKey = key;
                yield setCurrentTypeMenu(key);
            }
            yield setThreeDay();
            for (const item of menu.children) {
                const type = item.name
                if (!currentTypeMenu[type]) {
                    yield setCurrentTypeMenu(key);
                    continue;
                }
                currentTypeMenu[type].dom.click();
                yield sleep(500);
                for (const line of item.children) {
                    if (typeof line === "string") {
                        const dom = currentTypeMenu[type].menu.find(e => e.innerText === line)
                        if (!dom) {
                            console.log(`找不到 ${key}-${type}-${line}`)
                            continue;
                        } else {
                            dom.click()
                        }
                        yield sleep(500);
                        yield queryAndRender(
                            [key, type],
                            line
                        )
                    } else {
                        const typeChild = line.name;
                        const dom = currentTypeMenu[type].menu.find(e => e.innerText === line.name)
                        if (!dom) {
                            console.log(`找不到 ${key}-${type}-${typeChild}-${line.name}`)
                            continue;
                        } else {
                            dom.click()
                        }
                        yield sleep(500);
                        yield setCurrentCopyMenu()
                        for (const n of line.children) {
                            const dom = currentTypeMenuCopy[n]
                            if (!dom) {
                                console.log(`找不到 ${key}-${type}-${typeChild}-${n}`)
                                continue;
                            } else {
                                dom.click()
                            }
                            yield sleep(500);
                            yield queryAndRender(
                                [key, type, typeChild],
                                n
                            );
                        }
                    }
                }
            }
        }
    }
    let work;
    const start = async () => {
        work = factor();
        currentKey = "";
        while (status) {
            const { done, value } = work.next();
            try {
                if (done) work = factor();
                else await value
            } catch (e) {
                console.log("error", e)
            }
        }
    }
    const close = () => {
        clearTimeout(time);
    }
    const onclick = () => {
        status = !status;
        startBtn.innerText = status ? "暂停" : "开始"
        if (status) start()
        else close()
    }
    console.log(startBtn)
    startBtn.onclick = onclick
})()